var tool = require("./tool"),
    mail = require("./mail"),
    uri = require("url"),
    backHelper = require("./back2PrevHelper"),
    info,username, moduleName, access;

module.exports = function (next, onlineUrls, previewUrls) {
    require("shelljs/global");
    require("colors");
    
    info = require("../build.json/index.json");
    
    var prompt = require("prompt"),
        deployInfo = require("../../deploy-conf.json"),
        urls = [],
        execInfo;

    //回滚对应的预览机代码
    if (previewUrls) {
        urls = previewUrls.map(function (item) {
            var parse = uri.parse(item.receiver),
                href = parse.href.slice(0, parse.href.lastIndexOf("/"));
            return href + "/back2PrevResponse.php";
        });
    } else if (onlineUrls) {
        //回滚对应的线上代码
        urls = onlineUrls.map(function (item) {
            var parse = uri.parse(item.receiver),
                href = parse.href.slice(0, parse.href.lastIndexOf("/"));
            return href + "/back2PrevResponse.php";
        });
    }

    if (!urls.length) {
        console.log("back urls can't be empty...".red);
        process.exit(0);
    }

    moduleName = deployInfo.namespaces;

    tool.log("\nyour username is: ".green);
    execInfo = exec("whoami");

    if (execInfo.code == 0) {
        username = execInfo.output.replace("\n", "");

        if (info.access.indexOf(username) == -1) {
            console.log("you have no power to push to online!".red);
            process.exit(0);
        }

        if (onlineUrls) {
            prompt.start();
            prompt.get({
                properties: {
                    back: {
                        message: "将回滚线上服务器代码至当前上一个版本，是否回滚(y/n)",
                        required: true
                    }
                }
            }, function (err, result) {
                if (result.back == "y") {
                    startBack(urls, next);
                } else {
                    process.exit(0);
                }
            });
        } else {
            startBack(urls);
        }
    } else {
        process.exit(0);
    }
};

function startBack(urls, next) {
    backHelper({
        username: username,
        modulename: moduleName,
        urls: urls
    }, function (backSuccessArr, backFaildArr) {
        mail.sendMail({
            success: backSuccessArr,
            error: backFaildArr
        }, function () {
            if (next && next.length) {
                next.shift()(next);
            } else {
                typeof next == "function" && next();
            }
        }, 1);
    });
}